package com.haixee.parkdemo.openapi.controller;

import org.springdoc.core.AbstractSwaggerUiConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;

//@RestController
public class CommonController {

    @Autowired
    private DiscoveryClient discoveryClient;

    private final Set<String> notService = new HashSet<>(Arrays.asList("gateway", "openapi"));

    @GetMapping("/v3/api-docs/swagger-config")
    public Map<String, Object> v3swaggerConfigurations(ServerHttpRequest request) throws URISyntaxException {
        URI uri = request.getURI();
        URI url = new URI(uri.getScheme(), uri.getAuthority(), null, null, null);
        Map<String, Object> swaggerConfigMap = new LinkedHashMap<>();
        List<AbstractSwaggerUiConfigProperties.SwaggerUrl> swaggerUrls = new LinkedList<>();
        discoveryClient.getServices().stream().filter(serviceName -> !notService.contains(serviceName)).forEach(serviceName -> {
            swaggerUrls.add(new AbstractSwaggerUiConfigProperties.SwaggerUrl(serviceName, url + "/" + serviceName + "/v3/api-docs", serviceName));
        });
        swaggerConfigMap.put("urls", swaggerUrls);
        return swaggerConfigMap;
    }
}
